﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Core;
using BSCMFF.Web.UserControls.Selections;
using BSCMFF.Core.Exceptions.Database;
using BSCMFF.Core.EmailProvider;

namespace BSCMFF.Web.Pages.Administration
{
    public partial class UserManagement : MultiLanguagePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //RadGrid1.LocalizationPath = "~/App_GlobalResources";
            RadGrid1.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
        }
        protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            BSCEntities context = new BSCEntities();

            User u = new User();

            SetUserProperties(userControl, u);

            string origpassword = u.Password;
            u.Password = ComputeSHA512(origpassword);
            context.AddToUsers(u);

            try
            {
                context.SaveChanges();
                
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("COuldn't create employee: " + ex.Message);
            }
            try
            {
                EmailProvider.SendEmail(u.Email, "BSCMFF account", "Login: " + u.Login + " <br /> Password: " + origpassword);

            }
            catch
            {

            }
            //List<string> emails = new List<string>();
            //emails.Add(u.Email);

            //EmailProvider.SendEmailsThroughGmail(emails, "BSCMFF account", "Login: " + u.Login + " <br /> Password: " + origpassword);

            //u.Role = new Role();

            //u.Login = "agtwe";
            //u.Password = "adsg";
            //u.Role_FK = 1;
            //u.User_Setting_FK = 1;
            //UserManager um = new UserManager();
            //um.CreateUser(u);

            //context.Users.AddObject(u);


            //context.SaveChanges();

        }

        private static void SetUserProperties(UserControl userControl, User u)
        {
            u.Firstname = (userControl.FindControl("RadTextBoxFirstname") as RadTextBox).Text;
            u.Lastname = (userControl.FindControl("RadTextBoxLastname") as RadTextBox).Text;
            u.Email = (userControl.FindControl("RadTextBoxEmail") as RadTextBox).Text;
            u.Login = (userControl.FindControl("RadTextBoxLogin") as RadTextBox).Text;

            string password = (userControl.FindControl("TextBoxPassword") as RadTextBox).Text;
            if (password == "")
            {
                password = GeneratePassword();
            }
            u.Password = password;// ComputeSHA512(password);
            u.Role_FK = Convert.ToInt32((userControl.FindControl("ComboBoxRoles") as RadComboBox).SelectedValue);
            u.User_Setting_FK = 1;

            u.Job_Position = (userControl.FindControl("RadTextBoxJobPosition") as RadTextBox).Text;
            u.HireDate = (userControl.FindControl("RadDatePicker1") as RadDatePicker).SelectedDate;
            u.EmployeeID = (userControl.FindControl("RadTextBoxEmployeeID") as RadTextBox).Text;
            u.SBU_FK = Convert.ToInt32((userControl.FindControl("RadComboBoxDepartments") as RadComboBox).SelectedValue);

            //string ssal= (userControl.FindControl("RadNumericTextBoxSalary") as RadTextBox).Text;
            //int sal = 0;
            ////try
            ////{
            ////    double.TryParse(ssal, out sal);
            ////}
            ////catch{}
            u.Salary =  (decimal?)(userControl.FindControl("RadNumericTextBoxSalary") as RadNumericTextBox).Value;
            string mfk =(userControl.FindControl("RadComboBoxEmployee") as RadComboBox).SelectedValue;
            if(mfk != "")
            {
                u.Manager_FK = Int32.Parse(mfk);
            }

        }

        private static string ComputeSHA512(string s)
        {
            if (string.IsNullOrEmpty(s)) throw new ArgumentNullException();
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            buffer = System.Security.Cryptography.SHA512Managed.Create().ComputeHash(buffer);
            return System.Convert.ToBase64String(buffer).Substring(0, 86); // strip padding
        }

        protected static string GeneratePassword()
        {
            int passwordLength = 8;
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
            char[] chars = new char[passwordLength];
            Random rd = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            return new string(chars);
        }

        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);


            int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString());

            UserManager um = new UserManager();
            um.Delete(id);

            //BSCEntities context = new BSCEntities();

            //User u = (from user in context.Users
            //          where user.ID == id
            //          select user).Single();

            //context.Users.DeleteObject(u);
            //context.SaveChanges();
            RadGrid1.Rebind();
        }

        protected void RadGrid1_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);


            int user_ID = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString());
            BSCEntities context = new BSCEntities();

            //User u = (from user in context.Users
            //          where user.ID == id
            //          select user).Single();

            //Hashtable ht = new Hashtable();
            //ht["login"] = (userControl.FindControl("TextBoxLogin") as RadTextBox).Text;
            ////u.Login = (userControl.FindControl("TextBoxLogin") as RadTextBox).Text;
            //ht["password"] = (userControl.FindControl("TextBoxPassword") as RadTextBox).Text;            
            ////u.Password = (userControl.FindControl("TextBoxPassword") as RadTextBox).Text;
            //ht["role_fk"] = Convert.ToInt32((userControl.FindControl("ComboBoxRoles") as RadComboBox).SelectedValue);
            ////u.Role_FK = Convert.ToInt32((userControl.FindControl("ComboBoxRoles") as RadComboBox).SelectedValue);
            ////context.SaveChanges();

            //User u = new User();
            //u.ID = user_ID;

           // BSCEntities context = new BSCEntities();
            User u = (from users in context.Users
                      where users.ID == user_ID
                      select users).SingleOrDefault();

            SetUserProperties(userControl, u);

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("COuldn't update employee: " + ex.Message);
            }

            //UserManager um = new UserManager();
            //um.Update(u);
        }

        //protected void RadGrid1_SelectedIndexChanged(object source, GridCommandEventArgs e)
        //{
        //    Response.Redirect("UserList.aspx?EmployeeID=" + RadGrid1.SelectedValue);
        //}

        //protected void RadGrid1_SelectedIndexChanged1(object sender, EventArgs e)
        //{

        //}

        protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.Item != null && e.Item.ItemIndex != -1 && e.CommandName == "Select") //create new
            {
                int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString());
                Response.Redirect("../UserPages/EmployeeInfo.aspx?EmployeeID=" + id);
            }
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                int userID = Int32.Parse(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString());
                int currentUserID = (int)Session["loggedUserID"];

                if (userID == currentUserID)
                {
                    item["Delete"].Controls[0].Visible = false;
                }
            } 
        }

        //protected void ImageButtonImportUsers_Click(object sender, ImageClickEventArgs e)
        //{

        //}
    }
}